import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:ui';

class PresentPageApp extends StatelessWidget {
  const PresentPageApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      debugShowMaterialGrid: false,
      theme: ThemeData(
        primarySwatch: Colors.orange,
      ),
      home: PresentPage(),
    );
  }
}

const platform = const MethodChannel('willian.flutter.io/willian_present');

class PresentPage extends StatefulWidget {
  PresentPage({Key key}) : super(key: key);

  @override
  _PresentPageState createState() => _PresentPageState();
}

class _PresentPageState extends State<PresentPage> {

  int _counter = 0;

  void _incrementCounter(){
    setState(() {
      _counter++;
    });
  }

  String nativeBackString = 'Not return';

  Future<void> invokeNativeGetResult() async {
    String backString;
    try {
      // 调用原生方法并传参，以及等待原生返回结果数据
      var result = await platform.invokeMethod('getNativeResult', {'key1':'value1','key2':'value2'});
      backString = 'Native return $result';
    } on PlatformException catch (e) {
      backString = "Failed to get native return: '${e.message}'.";
    }

    setState(() {
      nativeBackString = backString;
    });
  }

  void dismiss(){
    // 直接调用原生方法
    platform.invokeMethod('dismiss');
  }

  void goToNativeSecondPage(){
    // 直接调用原生方法
    platform.invokeMethod('presentNativeSecondPage');
  }

  String mediaCall(BuildContext context){
    var media = MediaQuery.of(context);
    print(media.toString());
    print("设备像素密度:" + media.devicePixelRatio.toString());
    print(media.orientation);
    print("屏幕：" + media.size.toString());
    print('状态栏高度：' + media.padding.top.toString());
    return media.padding.toString();
  }

  Future<dynamic> _handel(MethodCall methodCall){
    String backNative = "failure";
    if(methodCall.method == 'flutterMedia'){
      print("参数：" + methodCall.arguments.toString());
      backNative = mediaCall(this.context);
    }
    return Future.value(backNative);
  }

  @override
  void initState() { 
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // flutter 注册原生监听方法
    platform.setMethodCallHandler(_handel);

    return Scaffold(
      appBar:AppBar(
        title:Text("present page 1"),
        leading: IconButton(
          icon: Icon(
            Icons.close,
          ),
          onPressed: (){
              dismiss();
          }
        ),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              nativeBackString,
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.bodyText1,
            ),
            RaisedButton(
              onPressed: dismiss,
              child: Text('Dismiss'),
            ),
            RaisedButton(
              onPressed: goToNativeSecondPage,
              child: Text('Go to native second page'),
            ),
            RaisedButton(
              onPressed: invokeNativeGetResult,
              child: Text('Invoke Native function get callback result'),
            ),
            RaisedButton(
              child: Text('Go to flutter second page'),
              onPressed: () {
                Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => SecondPageContent(),
                ));
              }
            ),
            Card(
              elevation: 4.0,
              shape: new RoundedRectangleBorder(
                  borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(16.0),
                  topRight: Radius.circular(16.0),
                  bottomLeft: Radius.circular(12.0),
                  bottomRight: Radius.circular(2.0),
              )),
              child: new IconButton(icon: Icon(Icons.add), onPressed: _incrementCounter),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // 
    );
  }
}

class SecondPageContent extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: Text('Second Present Page'),
      ),
        body: Center (
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              new Text('Second Present Content'),
              new RaisedButton(
                onPressed: (){
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) => ThirdPage(),
                    ),
                  );
                },
                child: Text('Go to Third Page'),
              ),
              new RaisedButton(
                onPressed: (){
                  //先关掉flutter里面的页面
                  SystemNavigator.pop();
                  //再回掉 直接调用原生方法
                  platform.invokeMethod('dismiss');
                },
                child: Text('Close Flutter Page'),
              ),
            ],
          ),
        )
    );
  }
}



class ThirdPage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: Text('ThirdPage'),
      ),
      body: new Center(
        child: Text('Third Page Content'),
      ),
    );
  }
}